package org.jaaksi.customviewdemo.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.util.AttributeSet
import android.view.View
import org.jaaksi.customviewdemo.R
import kotlin.math.roundToInt

class StarView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    var percent = 1f
    var highlightColor = Color.RED
    var drawableRes: Int = R.drawable.icon_heart

    private val bgDrawable by lazy {
        resources.getDrawable(drawableRes).apply {
            setBounds(0, 0, width, height)
        }
    }
    private val fgDrawable by lazy {
        resources.getDrawable(drawableRes).apply {
            setBounds(0, 0, width, height)
            setTint(highlightColor)
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        bgDrawable.draw(canvas)
        canvas.save()
        canvas.clipRect(0, 0, (width * percent).roundToInt(), height)
        fgDrawable.draw(canvas)
        canvas.restore()
    }
}